package com.gzyj.server.service;

import com.gzyj.data.common.VehicleIncrement;
import com.gzyj.jtt808.common.GPSPosition;
import com.gzyj.jtt808.v2013.protocol.JTT808_0x0200;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RoadLevelAlarmService {

    @Resource(name = "clusterRedisTemplate")
    private RedisTemplate<String, Object> clusterRedisTemplate;

    @Value("${redis.key.vehicle.lastposition}")
    private String VehicleLastPosition;

    public void processRoadLevelLimited(Object jtt0x0200, VehicleIncrement vehicleInfo, GPSPosition gpsPosition) {
        if (gpsPosition == null) {
            if (jtt0x0200 instanceof JTT808_0x0200) {
                JTT808_0x0200 pack = (JTT808_0x0200) jtt0x0200;
                gpsPosition = pack.transform();
            } else if (jtt0x0200 instanceof com.gzyj.jtt808.v2019.protocol.JTT808_0x0200) {
                com.gzyj.jtt808.v2019.protocol.JTT808_0x0200 pack = (com.gzyj.jtt808.v2019.protocol.JTT808_0x0200) jtt0x0200;
                gpsPosition = pack.transform();
            } else {
                return;
            }
        }


        if (clusterRedisTemplate.hasKey(VehicleLastPosition + vehicleInfo.getId())) {
            clusterRedisTemplate.expire(VehicleLastPosition + vehicleInfo.getId(),8, TimeUnit.HOURS);
            long len = clusterRedisTemplate.opsForList().size(VehicleLastPosition + vehicleInfo.getId());
            clusterRedisTemplate.opsForList().rightPush(VehicleLastPosition + vehicleInfo.getId(), gpsPosition);
            if (len > 3) {
                long cha = len - 3;
                for (int i = 0; i <= cha; i++) {
                    clusterRedisTemplate.opsForList().leftPop(VehicleLastPosition + vehicleInfo.getId());
                }

            }

        } else {
            clusterRedisTemplate.opsForList().rightPush(VehicleLastPosition + vehicleInfo.getId(), gpsPosition);
            clusterRedisTemplate.expire(VehicleLastPosition + vehicleInfo.getId(),8, TimeUnit.HOURS);
        }


    }
}
